from cProfile import label
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#读取数据
file = pd.read_csv("./WND-class/class1-one_value_regrassion/ex1data1.txt",names=['population','profit'])
file.plot.scatter(x = 'population',y = 'profit')
#打印一下我们要预测的东西
plt.show()
#插入一个列方便以后做矩阵运算
file.insert(0,'ones',1)
X = file.iloc[:,:-1]
y = file.iloc[:,-1:]
X = X.values
y = y.values
def costFunction(X,y,theta):
    inner = np.power(X @ theta - y,2)
    return np.sum(inner) / (2 * len(X))
theta = np.zeros((2,1))
cost_init = costFunction(X,y,theta)

def gradientDescent(X,y,theta,alpha,iters):
    costs = []
    for i in range(iters):
        theta = theta - (X.T @ (X @ theta - y)) * alpha / len(X)
        cost = costFunction(X,y,theta)
        costs.append(cost)

        if i % 100:
            print(cost)
    return theta,costs

alpha = 0.002
iters = 2000
theta,costs = gradientDescent(X,y,theta,alpha,iters)
fig,ax = plt.subplots()
ax.plot(np.arange(iters),costs,'b')
ax.set(xlabel='iters',ylabel='costs',title='cost vs iters')
plt.show()

x = np.linspace(y.min(),y.max(),100)
_y = theta[0,0] + theta[1,0] * x

fig,ax = plt.subplots()
ax.scatter(X[:,1],y,label='training data')
ax.plot(x,_y,'r',label='predict')
ax.legend()
ax.set(xlabel='population',ylabel='profit')
plt.show()